package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
)

func main() {
	ln, err := net.Listen("tcp", ":80")
	myerr(err)
	for {
		conn, err := ln.Accept()
		myerr(err)
		go handle(conn)
		go storage(conn)
	}
}

type client chan string

var (
	clients  = make(map[string]client)	//用于存储消息
	messages = make(chan string)		//用于传递消息
)

//消息存储函数
func storage(c net.Conn) {
//	fmt.Println("storage begin")
	ID := c.RemoteAddr().String()	//用于标识
	cli := make(client)
	for {
		select {
		case msg := <-messages:
//			go func() {
//				<-clients[ID]
//			}()
			clients[ID] = cli
			log.Println("===消息存储成功===")
			cli <- msg	//这里会阻塞，直到有对象读取通道
		}
	}
}

//客户端处理函数
func handle(c net.Conn) {
	fmt.Println("handle begin")
	go writeToClient(c, messages)
	input := bufio.NewScanner(c)
	for input.Scan() {
		messages <- input.Text()
		messages <- input.Text()
		fmt.Println("handle-response:", input.Text())
	}
}

//用于广播消息
func broadcast() {

}

//把消息写回到客户端
func writeToClient(c net.Conn, ch chan string) {
	//	for msg := range ch {
	//		fmt.Fprintln(c, "wtc-response:" + msg)
	//	}
	fmt.Fprintln(c, "wtc-response:"+<-ch)
}

//错误处理函数
func myerr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
